/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.ejb.dao.impl;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TransactionRequiredException;

import cz.muni.fi.pa165.creatures.ejb.dao.CreatureDAOLocal;
import cz.muni.fi.pa165.creatures.ejb.model.Creature;

/**
 * This class represents the implementation of all basic operations upon {@link cz.muni.fi.pa165.creatures.model.Creature}
 * instances.
 *
 * @author hulek
 */
@Stateless
public class CreatureDAO implements CreatureDAOLocal {

    @PersistenceContext(unitName = "creatures-test-unit")
    private EntityManager em;

    private static final Logger logger = Logger.getLogger(CreatureDAO.class.getName());

    @Override
    public void create(Creature creature) {
        try {
            DAOUtils.notNull(creature);
            em.persist(creature);
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, "Unable to create a creature. Creature to persist is a null object.");
        } catch (EntityExistsException ex) {
            logger.log(Level.INFO, "Unable to create a creature. Creature to persist already exists.");
        } catch(Exception ex) {
            logger.log(Level.INFO, ex.getMessage());
        }
    }

    @Override
    public void remove(Creature creature) {
        try {
            DAOUtils.notNull(creature);
            Creature toRemove = em.find(Creature.class, creature.getId());
            em.remove(toRemove);
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, "Unable to create a creature. Creature to remove is a null object.");
        }
    }

    @Override
    public void update(Creature creature) {
        try {
            DAOUtils.notNull(creature);
            em.merge(creature);
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, "Unable to remove the creature. It is not an entity or it is remove entity.");
        } catch (TransactionRequiredException ex) {
            logger.log(Level.INFO, "There is no transaction and and container-managed entity manager is of type "
                    + "PersistenceContextType.TRANSACTION");
        }
    }

    @Override
    public Creature get(Long id) {
        try {
            DAOUtils.notNull(id);
            Creature creature = em.find(Creature.class, id);
            return creature;
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, "Id for getting the creature is null.");
            return null;
        }
    }

    @Override
    public Long getCount() {
        try {
            Query q = em.createQuery("select count(o) from Creature as o");
            return ((Long) q.getSingleResult());
        } catch (Exception ex) {
            logger.log(Level.INFO, ex.getMessage());
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Creature> getAll() {
        try {
            Query q = em.createQuery("select c from Creature c");
            return q.getResultList();
        } catch (Exception ex) {
            logger.log(Level.INFO, ex.getMessage());
            return null;
        }
    }

    @Override
    public Creature getByName(String name) {
        try {
            DAOUtils.notNull(name);
            Query q = em.createQuery("select o from Creature as o where o.name = :name");
            q.setParameter("name", name);
            return (Creature) q.getResultList().get(0);
        } catch (Exception ex) {
            logger.log(Level.INFO, ex.getMessage());
            return null;
        }
    }
}
